<?php

namespace app\admin\service;

use app\admin\validate\AdminUserValidate;
use support\spark\exception\ApiException;
use support\spark\model\system\AdminUser;

class AdminService
{
    /**
     * 获取管理员列表
     * @param $param
     * @return array
     */
    public function getList($param)
    {
        $limit = $param['limit'];
        $nickname = $param['nickname'];

        $where = [];
        if (!empty($nickname)) {
            $where[] = ['nickname', 'like', '%' . $nickname . '%'];
        }
        $adminUserModel = new AdminUser();
        $list = $adminUserModel->getPaginateList($where, ['*'], ['id' => 'desc'], ['role'], $limit);
        foreach ($list['data'] as $key => $item) {
            if ($item['role_id'] == 0) {
                $list['data'][$key]['role_name'] = '超级管理员';
            }
        }
        return dataReturn(0, 'success', $list);
    }


    /**
     * 添加管理员
     * @param $param
     */
    public function addAdmin($param)
    {
        if (isset($param['file'])) {
            unset($param['file']);
        }
        $validate = new AdminUserValidate();
        if (!$validate->check($param)) {
            throw  new  ApiException($validate->getError(), -1);
        }
        $adminUserModel = new AdminUser();
        $has = $adminUserModel->checkUnique([
            'name' => $param['name']
        ]);
        if (!empty($has)) {
            throw  new  ApiException('该管理员已经存在', -1);
        }
        $param['password'] = makePassword($param['password']);
        $param['salt'] = config('shop.salt');
        $param['create_time'] = now();
        $param['update_time'] = now();
        $adminUserModel->insertOne($param);
        return dataReturn(0, '添加成功');
    }


    /**
     * 编辑管理员
     * @param $param
     * @return array|\think\response\Json
     */
    public function editAdmin($param)
    {
        if (isset($param['file'])) {
            unset($param['file']);
        }
        $validate = new AdminUserValidate();
        if (!$validate->scene('edit')->check($param)) {
            throw  new  ApiException($validate->getError(), -1);
        }
        if (!empty($param['password'])) {
            $param['password'] = makePassword($param['password']);
            $param['salt'] = config('shop.salt');
        } else {
            unset($param['password']);
        }

        $adminUserModel = new AdminUser();
        $where[] = ['name', '=', $param['name']];
        $where[] = ['id', '<>', $param['id']];
        $has = $adminUserModel->checkUnique($where);

        if (!empty($has)) {
            throw  new  ApiException('该管理员已经存在', -1);
        }
         $adminUserModel->updateById($param, $param['id']);
        return dataReturn(0, '编辑成功');
    }
}